package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"time"
)

func Register(address string, port int, name string, tags []string, id string) error {

	config := api.DefaultConfig()
	config.Address = "10.26.10.121:8500"
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	check := &api.AgentServiceCheck{
		HTTP:                           "http://10.26.10.121:8021/health",
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "15s",
	}
	registration := new(api.AgentServiceRegistration)
	registration.Address = address
	registration.Name = name
	registration.Port = port
	registration.Tags = tags
	registration.ID = id
	registration.Check = check

	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}
	return nil
}

func AllServices() {
	config := api.DefaultConfig()
	config.Address = "10.26.10.121:8500"
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	services, err := client.Agent().Services()
	if err != nil {
		panic(err)
	}
	for _, v := range services {
		fmt.Println(v)
	}
}

func FilterService() {

	config := api.DefaultConfig()
	config.Address = "10.26.10.121:8500"
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	data, err := client.Agent().ServicesWithFilter(`Service == "user_srv"`)
	if err != nil {
		panic(err)
	}
	for k, _ := range data {
		fmt.Println(k)
	}
}

func main() {
	_ = Register("10.26.10.121", 8021, "user-test", []string{"mxshop", "bobby"}, "user-test")
	AllServices()
	//FilterService()
	time.Sleep(time.Minute * 10)
}
